import requests
import base64
import ddddocr


def image_to_code(img_path):
    ocr = ddddocr.DdddOcr(show_ad=False)
    with open(img_path, "rb") as f:
        result = ocr.classification(f.read())
        return result


def get_verifycode():
    url = 'https://testapi.hnilab.com/api/Login/GenerateVerifyCode'
    res = requests.get(url)
    res = res.json()['rows']
    key = res['key']
    codeimage = res['codeimage'].split(",")[1]
    codeimage = base64.b64decode(codeimage)
    img_path = "../datas/code/code.png"
    with open(img_path, "wb") as f:
        f.write(codeimage)
    code = image_to_code(img_path)
    return {
        "verifycode": code,
        "key": key
    }


def get_user_token():
    url = "https://testapi.hnilab.com/api/Login/Login"
    json_data = {
        "account": "18860262882",
        "password": "liyu0228..",

    }
    key_code = get_verifycode()
    json_data.update(key_code)
    res = requests.post(url=url, json=json_data)
    if res.status_code == 200:
        if res.json()["code"] == 200:
            token = res.json()["rows"]['accesstoken']
            return token
        else:
            print(res.json())
    else:
        print(res.status_code)


# get_user_token()


def get_user_info():
    url = "https://testapi.hnilab.com/api/User/GetTokenUser"
    token = get_user_token()
    headers = {
        "Authorization": f"Bearer {token}"
    }
    res = requests.get(url=url, headers=headers)
    if res.status_code == 200:
        print(res.json()["rows"]["username"])


# get_token_user("D2D07C67C828ED9F80EC6F67E9F5929803625550EF9594332FA1AD82B11F2E26")

if __name__ == '__main__':
    get_user_info()
